package com.usian.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.usian.fegin.AuthorFegin;
import com.usian.model.comment.CommentSaveDto;
import com.usian.model.comment.pojos.ApComment;
import com.usian.model.comment.pojos.ApCommentLike;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.user.pojos.ApUser;
import com.usian.service.CommentLikeService;
import com.usian.service.CommentService;
import com.usian.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class CommentLikeServiceImpl implements CommentLikeService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private AuthorFegin authorFeginl;


    @Override
    public ResponseResult nice_nonice(CommentSaveDto dto) {

        //判断参数是否为空
        if(dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //获取用户id
        ApUser user = AppThreadLocalUtils.getUser();
        //判断是点赞还是取消点赞
        if(dto.getOperation()==0){
            //添加ApCommentLike表
            ApCommentLike apCommentLike = new ApCommentLike();
            apCommentLike.setOperation(dto.getOperation());
            apCommentLike.setCreatedTime(new Date());
            apCommentLike.setAuthorId(user.getId());
            apCommentLike.setCommentId(dto.getCommentId());
            mongoTemplate.insert(apCommentLike);

            //修改点赞次数
            //完成ApComment的likes查询
            Query query = new Query(Criteria.where("Id").is(dto.getCommentId()));
            ApComment one = mongoTemplate.findOne(query, ApComment.class);
            Integer likes = one.getLikes();

            //自增点赞次数
            likes++;

            //完成修改ApComment
            Update likes1 = Update.update("likes", likes);
            mongoTemplate.updateFirst(query,likes1,ApComment.class);
        }else{
            //删除ApCommentLike表
            Query query = new Query(Criteria.where("commentId").is(dto.getCommentId()));
            mongoTemplate.remove(query,ApCommentLike.class);

            //完成ApComment的likes查询
            Query query1 = new Query(Criteria.where("Id").is(dto.getCommentId()));
            ApComment one = mongoTemplate.findOne(query1, ApComment.class);
            Integer likes = one.getLikes();
            //自减点赞次数
            likes--;

            //完成修改ApComment
            Update likes1 = Update.update("likes", likes);
            mongoTemplate.updateFirst(query1,likes1,ApComment.class);
        }



        return null;
    }
}
